//
//  IAPPurchasedItem.swift
//  GhostWorld
//
//  Created by Kam on 2018/7/30.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let entityName = CoreDataEntityName.iapPurchasedItem.rawValue
private let context = CoreDataHelper.getContext()

extension IAPPurchasedItem {
  static func get(contentType: String, id: Int) throws -> IAPPurchasedItem? {
    let request = NSFetchRequest<IAPPurchasedItem>()
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    request.entity = entity
    request.predicate = NSPredicate(format: "contentType = %@ && id = %@", contentType, "\(id)")
    do {
      let iapPurchasedItem = try context.fetch(request).first
      return iapPurchasedItem
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  static func add(date: Date, contentType: String, id: String, name: String, coverURLString: String) throws {
    let iapPurchasedItem = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! IAPPurchasedItem
    iapPurchasedItem.date = date
    iapPurchasedItem.contentType = contentType
    iapPurchasedItem.id = id
    iapPurchasedItem.name = name
    iapPurchasedItem.coverURLString = coverURLString
    do {
      try context.save()
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  static func removeAll() throws {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let removeRequest = NSBatchDeleteRequest(fetchRequest: request)
    do {
      try context.execute(removeRequest)
      try context.save()
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
}
